import Message from 'tdesign-miniprogram/message/index';
import { userAPI } from '~/api/user';
import { novelAPI } from '~/api/novel';
import userProfileAPI from '~/api/userProfile';
import badgeAPI from '~/api/badge';
import rewardAPI from '~/api/reward';
import { interactionAPI } from '~/api/interaction';
import { processImageUrl } from '~/utils/image-helper';
import authUtils from '~/utils/auth';

// 获取应用实例
const app = getApp();

Page({
  data: {
    // 用户信息
    userInfo: {},
    // 用户详细信息
    userProfile: {},
    
    // Tab 相关
    currentTab: 'posts',
    tabs: [
      { id: 'posts', name: '我的书摘', icon: '📖' },
      { id: 'novels', name: '我的小说', icon: '✍️' },
      { id: 'favorites', name: '我的收藏', icon: '⭐' }
    ],
    
    // 内容数据
    myPosts: [],
    myNovels: [],
    myFavorites: [],
    
    // 我的徽章
    myBadges: [],
    
    // 徽章弹窗
    showBadgeDetail: false,
    selectedBadge: null
  },

  onLoad() {
    // 确保用户已登录后再加载数据
    this.ensureUserLogin();
  },

  onShow() {
    // 页面显示时刷新数据
    this.refreshData();
  },

  /**
   * 确保用户已登录
   */
  ensureUserLogin() {
    const userInfo = wx.getStorageSync('userInfo');
    const userId = wx.getStorageSync('userId');
    
    if (userInfo && userId) {
      console.log('用户已登录，用户ID:', userId);
      // 更新全局数据
      app.globalData.userInfo = userInfo;
      app.globalData.userId = userId;
      
      // 加载页面数据
      this.loadUserInfo();
      this.loadUserProfile();
      this.loadMyPosts();
      this.loadMyNovels();
      this.loadMyFavorites();
      this.loadMyBadges();
    } else {
      console.log('用户未登录，跳转到登录页面');
      wx.reLaunch({
        url: '/pages/login/login'
      });
    }
  },

  /**
   * 加载用户信息
   */
  async loadUserInfo() {
    try {
      // 检查用户是否已登录
      if (!authUtils.isLoggedIn()) {
        console.log('用户未登录，跳转到登录页面');
        authUtils.redirectToLogin();
        return;
      }
      
      // 获取真实用户信息
      const currentUser = authUtils.getCurrentUser();
      if (currentUser && currentUser.userInfo) {
        // 处理头像URL
        const userInfo = { ...currentUser.userInfo };
        userInfo.avatarUrl = processImageUrl(userInfo.avatarUrl, '/static/avatar1.png');
        this.setData({ userInfo });
      } else {
        // 如果本地没有用户信息，尝试从全局数据获取
        const globalUserInfo = app.globalData.userInfo;
        if (globalUserInfo) {
          // 处理头像URL
          const userInfo = { ...globalUserInfo };
          userInfo.avatarUrl = processImageUrl(userInfo.avatarUrl, '/static/avatar1.png');
          this.setData({ userInfo });
        } else {
          console.error('无法获取用户信息');
          Message.error({
            context: this,
            offset: [20, 32],
            duration: 3000,
            content: '用户信息获取失败，请重新登录'
          });
        }
      }
    } catch (error) {
      console.error('加载用户信息失败:', error);
      Message.error({
        context: this,
        offset: [20, 32],
        duration: 3000,
        content: '加载用户信息失败，请重试'
      });
    }
  },

  /**
   * 加载用户详细信息
   */
  async loadUserProfile() {
    try {
      // 检查用户是否已登录
      if (!authUtils.isLoggedIn()) {
        console.log('用户未登录，无法获取用户档案');
        return;
      }
      
      // 调用真实 API 获取用户档案信息
      const profileRes = await userProfileAPI.getMyProfile();
      if (profileRes.code === 200) {
        const userProfile = profileRes.data;
        console.log('用户档案数据:', userProfile);
        
        // 处理用户头像URL
        const avatarUrl = processImageUrl(userProfile.avatarUrl, '/static/avatar1.png');
        
        this.setData({ 
          userProfile: {
            id: userProfile.userId,
            nickname: userProfile.nickname,
            avatar: avatarUrl,
            title: userProfile.title,
            signature: userProfile.signature,
            level: userProfile.level
          },
          stats: userProfile.stats,
          // 同时更新userInfo中的头像URL，确保显示正确
          'userInfo.avatarUrl': avatarUrl
        });
      } else {
        throw new Error(profileRes.message || '获取用户档案失败');
      }
    } catch (error) {
      console.error('加载用户详细信息失败:', error);
      Message.error({
        context: this,
        offset: [20, 32],
        duration: 3000,
        content: '加载用户信息失败，请重试'
      });
    }
  },

  /**
   * 加载我的书摘
   */
  async loadMyPosts() {
    try {
      // 检查用户是否已登录
      if (!authUtils.isLoggedIn()) {
        console.log('用户未登录，无法获取书摘数据');
        this.setData({ myPosts: [] });
        return;
      }
      
      // 调用真实 API 获取用户书摘
      const postsRes = await userAPI.getUserPosts();
      if (postsRes.code === 200) {
        // 检查数据结构
        const postsData = postsRes.data;
        console.log('书摘数据:', postsData);
        
        // 确保数据是数组
        const postsList = Array.isArray(postsData) ? postsData : [];
        
        const myPosts = postsList.map(post => ({
          id: post.quoteId ? post.quoteId.toString() : 'unknown',
          content: post.content || '',
          userFeel: post.userFeel || '',
          isExpanded: false,
          isThoughtsExpanded: false,
          book: {
            title: post.bookTitle || '未知书籍',
            author: post.bookAuthor || '未知作者',
            coverUrl: processImageUrl(post.bookCoverUrl, '/static/home/card0.png')
          }
        }));
        
        this.setData({ myPosts });
      } else {
        throw new Error(postsRes.message || '获取书摘失败');
      }
    } catch (error) {
      console.error('加载我的书摘失败:', error);
      // 如果API失败，使用空数组而不是mock数据
      this.setData({ myPosts: [] });
    }
  },

  /**
   * 加载我的小说
   */
  async loadMyNovels() {
    try {
      // 检查用户是否已登录
      if (!authUtils.isLoggedIn()) {
        console.log('用户未登录，无法获取小说数据');
        this.setData({ myNovels: [] });
        return;
      }
      
      // 调用真实 API 获取用户参与的小说
      const novelsRes = await novelAPI.getMyParticipatedNovels({ page: 1, pageSize: 10 });
      if (novelsRes.code === 200) {
        // 检查数据结构，后端直接返回List，不是分页结果
        const novelsData = novelsRes.data;
        console.log('小说数据:', novelsData);
        
        // 确保数据是数组
        const novelsList = Array.isArray(novelsData) ? novelsData : (novelsData?.list || []);
        
        const myNovels = novelsList.map(novel => ({
          id: novel.id ? novel.id.toString() : 'unknown',
          title: novel.title || '未知小说',
          coverUrl: processImageUrl(novel.coverUrl, '/static/home/card2.png'),
          latestChapter: novel.currentChapterCount || 0,
          status: novel.status || 2, // 默认为进行中
          statusText: novel.status === 1 ? '招募中' : novel.status === 2 ? '进行中' : '已完结'
        }));
        
        this.setData({ myNovels });
      } else {
        throw new Error(novelsRes.message || '获取小说失败');
      }
    } catch (error) {
      console.error('加载我的小说失败:', error);
      // 如果API失败，使用空数组而不是mock数据
      this.setData({ myNovels: [] });
    }
  },

  /**
   * 加载我的收藏
   */
  async loadMyFavorites() {
    try {
      // 检查用户是否已登录
      if (!authUtils.isLoggedIn()) {
        console.log('用户未登录，无法获取收藏数据');
        this.setData({ myFavorites: [] });
        return;
      }
      
      // 调用收藏API获取用户收藏
      const favoritesRes = await interactionAPI.getUserFavorites();
      if (favoritesRes.code === 200) {
        // 检查数据结构
        const favoritesData = favoritesRes.data;
        console.log('收藏数据:', favoritesData);
        
        // 确保数据是数组
        const favoritesList = Array.isArray(favoritesData) ? favoritesData : (favoritesData?.list || []);
        
        const myFavorites = favoritesList.map(favorite => ({
          id: favorite.targetId ? favorite.targetId.toString() : 'unknown',
          title: favorite.targetTitle || '书摘',
          content: favorite.targetContent || '',
          type: '书摘', // 现在只显示书摘
          imageUrl: processImageUrl(favorite.targetImageUrl, '/static/home/card0.png'),
          createdAt: favorite.createdAt || new Date().toISOString(),
          // 书摘收藏的数据结构
          book: {
            title: favorite.bookTitle || '未知书籍',
            author: favorite.bookAuthor || '未知作者',
            coverUrl: processImageUrl(favorite.bookCoverUrl || favorite.targetImageUrl, '/static/home/card0.png')
          },
          user: {
            nickname: favorite.creatorNickname || '用户'
          },
          favoriteTime: favorite.favoriteTime || (favorite.createdAt ? favorite.createdAt.substring(0, 10) : '')
        }));
        
        this.setData({ myFavorites });
      } else {
        throw new Error(favoritesRes.message || '获取收藏失败');
      }
    } catch (error) {
      console.error('加载我的收藏失败:', error);
      this.setData({ myFavorites: [] });
    }
  },

  /**
   * 加载我的徽章
   */
  async loadMyBadges() {
    try {
      // 检查用户是否已登录
      if (!authUtils.isLoggedIn()) {
        console.log('用户未登录，无法获取徽章数据');
        this.setData({ myBadges: [] });
        return;
      }
      
      // 调用真实 API 获取用户徽章
      const badgesRes = await badgeAPI.getMyBadges();
      if (badgesRes.code === 200) {
        // 检查数据结构
        const badgesData = badgesRes.data;
        console.log('徽章数据:', badgesData);
        
        // 确保数据是数组
        const badgesList = Array.isArray(badgesData) ? badgesData : [];
        
        const myBadges = badgesList.map(badge => ({
          id: badge.badgeId ? badge.badgeId.toString() : 'unknown',
          name: badge.name || '未知徽章',
          icon: processImageUrl(badge.iconUrl, '/static/home/card0.png'),
          category: badge.category || '未分类',
          description: badge.description || '',
          requirement: badge.requirement || '',
          obtained: badge.obtained || false,
          earnedAt: badge.earnedAt ? new Date(badge.earnedAt).getTime() : null
        }));
        
        this.setData({ myBadges });
      } else {
        throw new Error(badgesRes.message || '获取徽章失败');
      }
    } catch (error) {
      console.error('加载我的徽章失败:', error);
      Message.error({
        context: this,
        offset: [20, 32],
        duration: 3000,
        content: '加载徽章失败，请重试'
      });
      this.setData({ myBadges: [] });
    }
  },


  /**
   * 刷新数据
   */
  async refreshData() {
    await this.loadUserInfo();
    await this.loadUserProfile();
    await this.loadMyPosts();
    await this.loadMyNovels();
    await this.loadMyFavorites();
    await this.loadMyBadges();
  },

  /**
   * 切换 Tab
   */
  switchTab(e) {
    const tabId = e.currentTarget.dataset.tab;
    this.setData({ currentTab: tabId });
  },

  /**
   * 徽章点击
   */
  async onBadgeTap(e) {
    const badge = e.currentTarget.dataset.badge;
    
    try {
      // 获取徽章详细信息
      const badgeDetailRes = await badgeAPI.getBadgeDetail(badge.id);
      if (badgeDetailRes.code === 200) {
        const badgeDetail = badgeDetailRes.data;
        this.setData({
          selectedBadge: {
            ...badge,
            ...badgeDetail
          },
          showBadgeDetail: true
        });
      } else {
        throw new Error(badgeDetailRes.message || '获取徽章详情失败');
      }
    } catch (error) {
      console.error('获取徽章详情失败:', error);
      Message.error({
        context: this,
        offset: [20, 32],
        duration: 3000,
        content: '获取徽章详情失败，请重试'
      });
    }
  },

  /**
   * 关闭徽章详情
   */
  closeBadgeDetail() {
    this.setData({
      showBadgeDetail: false,
      selectedBadge: null
    });
  },


  /**
   * 徽章弹窗状态变化
   */
  onBadgePopupChange(e) {
    if (!e.detail.visible) {
      this.closeBadgeDetail();
    }
  },

  /**
   * 上传头像
   */
  uploadAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        this.uploadAvatarToServer(tempFilePath);
      },
      fail: (err) => {
        console.error('选择头像失败:', err);
        Message.error({
          context: this,
          offset: [20, 32],
          duration: 2000,
          content: '选择头像失败，请重试'
        });
      }
    });
  },

  /**
   * 上传头像到服务器
   */
  async uploadAvatarToServer(filePath) {
    try {
      wx.showLoading({
        title: '上传中...',
        mask: true
      });

      // 先上传文件到服务器
      const uploadResult = await this.uploadFileToServer(filePath);
      
      // 然后更新用户头像信息
      const processedAvatarUrl = processImageUrl(uploadResult.fileUrl);
      const updateData = {
        id: wx.getStorageSync('userId'),
        openid: wx.getStorageSync('openid'),
        nickName: this.data.userInfo.nickName,
        avatarUrl: processedAvatarUrl,
        gender: this.data.userInfo.gender || 0,
        country: this.data.userInfo.country || '',
        province: this.data.userInfo.province || '',
        city: this.data.userInfo.city || '',
        language: this.data.userInfo.language || 'zh_CN'
      };

      const request = require('~/api/request.js').default;
      const updateResponse = await request('/user/updateUserAvatar', 'POST', updateData);
      
      if (updateResponse.code === 200) {
        // 更新本地数据
        this.setData({
          'userInfo.avatarUrl': processedAvatarUrl
        });
        
        // 更新本地存储
        const currentUserInfo = wx.getStorageSync('userInfo');
        currentUserInfo.avatarUrl = processedAvatarUrl;
        wx.setStorageSync('userInfo', currentUserInfo);

        wx.hideLoading();
        Message.success({
          context: this,
          offset: [20, 32],
          duration: 2000,
          content: '头像更新成功'
        });
      } else {
        throw new Error(updateResponse.message || '更新头像失败');
      }
    } catch (error) {
      wx.hideLoading();
      console.error('上传头像失败:', error);
      Message.error({
        context: this,
        offset: [20, 32],
        duration: 2000,
        content: '头像上传失败，请重试'
      });
    }
  },

  /**
   * 上传文件到服务器
   */
  uploadFileToServer(filePath) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: `${require('~/config/index.js').default.baseUrl}/file/upload/image`,
        filePath: filePath,
        name: 'file',
        header: {
          'Authorization': `Bearer ${wx.getStorageSync('access_token')}`
        },
        success: (res) => {
          try {
            const data = JSON.parse(res.data);
            if (data.code === 200) {
              resolve({ fileUrl: data.data });
            } else {
              reject(new Error(data.message || '上传失败'));
            }
          } catch (e) {
            reject(new Error('解析响应失败'));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  },

  /**
   * 更新昵称
   */
  async updateNickname(e) {
    const newNickname = e.detail.value.trim();
    if (!newNickname) {
      Message.error({
        context: this,
        offset: [20, 32],
        duration: 2000,
        content: '昵称不能为空'
      });
      return;
    }

    if (newNickname === this.data.userInfo.nickName) {
      return; // 没有变化，不需要更新
    }

    try {
      wx.showLoading({
        title: '更新中...',
        mask: true
      });

      // 调用后端更新用户信息API
      const updateData = {
        id: wx.getStorageSync('userId'),
        openid: wx.getStorageSync('openid'),
        nickName: newNickname,
        avatarUrl: this.data.userInfo.avatarUrl,
        gender: this.data.userInfo.gender || 0,
        country: this.data.userInfo.country || '',
        province: this.data.userInfo.province || '',
        city: this.data.userInfo.city || '',
        language: this.data.userInfo.language || 'zh_CN'
      };

      const request = require('~/api/request.js').default;
      const response = await request('/user/updateUserAvatar', 'POST', updateData);
      
      if (response.code === 200) {
        // 更新本地数据
        this.setData({
          'userInfo.nickName': newNickname
        });
        
        // 更新本地存储
        const currentUserInfo = wx.getStorageSync('userInfo');
        currentUserInfo.nickName = newNickname;
        wx.setStorageSync('userInfo', currentUserInfo);
        
        // 更新全局数据
        const app = getApp();
        if (app.globalData.userInfo) {
          app.globalData.userInfo.nickName = newNickname;
        }

        wx.hideLoading();
        Message.success({
          context: this,
          offset: [20, 32],
          duration: 2000,
          content: '昵称更新成功'
        });
      } else {
        throw new Error(response.message || '更新昵称失败');
      }
    } catch (error) {
      wx.hideLoading();
      console.error('更新昵称失败:', error);
      Message.error({
        context: this,
        offset: [20, 32],
        duration: 2000,
        content: '昵称更新失败，请重试'
      });
    }
  },

  /**
   * 更新个性签名
   */
  async updateSignature(e) {
    const newSignature = e.detail.value.trim();
    
    if (newSignature === this.data.userProfile.signature) {
      return; // 没有变化，不需要更新
    }

    try {
      wx.showLoading({
        title: '更新中...',
        mask: true
      });

      // 调用后端更新个性签名API
      const response = await userProfileAPI.updateSignature(newSignature);
      
      if (response.code === 200) {
        // 更新本地数据
        this.setData({
          'userProfile.signature': newSignature
        });

        wx.hideLoading();
        Message.success({
          context: this,
          offset: [20, 32],
          duration: 2000,
          content: '个性签名更新成功'
        });
      } else {
        throw new Error(response.message || '更新个性签名失败');
      }
    } catch (error) {
      wx.hideLoading();
      console.error('更新个性签名失败:', error);
      Message.error({
        context: this,
        offset: [20, 32],
        duration: 2000,
        content: '个性签名更新失败，请重试'
      });
    }
  },


  /**
   * 查看我的小说
   */
  viewMyNovels() {
    this.setData({ currentTab: 'novels' });
  },

  /**
   * 查看我的收藏
   */
  viewMyFavorites() {
    this.setData({ currentTab: 'favorites' });
  },


  /**
   * 查看小说详情
   */
  viewNovelDetail(e) {
    const novel = e.currentTarget.dataset.novel;
    wx.navigateTo({
      url: `/pages/novel-detail/index?novelId=${novel.id}`
    });
  },



  /**
   * 奖励中心
   */
  async goRewardCenter() {
    try {
      // 先获取奖励中心数据
      const rewardCenterRes = await rewardAPI.getRewardCenter();
      if (rewardCenterRes.code === 200) {
        // 将数据存储到全局，供奖励中心页面使用
        app.globalData.rewardCenterData = rewardCenterRes.data;
        
        wx.navigateTo({
          url: '/pages/reward-center/index'
        });
      } else {
        throw new Error(rewardCenterRes.message || '获取奖励中心数据失败');
      }
    } catch (error) {
      console.error('前往奖励中心失败:', error);
      Message.error({
        context: this,
        offset: [20, 32],
        duration: 3000,
        content: '加载奖励中心失败，请重试'
      });
    }
  },

  /**
   * 设置
   */
  goSettings() {
    console.log('点击设置按钮');
    wx.navigateTo({
      url: '/pages/setting/index',
      success: () => {
        console.log('成功跳转到设置页面');
      },
      fail: (err) => {
        console.error('跳转设置页面失败:', err);
        Message.error({
          context: this,
          offset: [20, 32],
          duration: 2000,
          content: '打开设置页面失败，请重试'
        });
      }
    });
  },


  /**
   * 展开/收起书摘内容
   */
  onExpandContent(e) {
    const { quoteId } = e.currentTarget.dataset;
    const { myPosts } = this.data;
    const postIndex = myPosts.findIndex(post => post.id === quoteId);
    
    if (postIndex !== -1) {
      myPosts[postIndex].isExpanded = !myPosts[postIndex].isExpanded;
      this.setData({ myPosts: [...myPosts] });
    }
  },

  /**
   * 展开/收起感想内容
   */
  onExpandThoughts(e) {
    const { quoteId } = e.currentTarget.dataset;
    const { myPosts } = this.data;
    const postIndex = myPosts.findIndex(post => post.id === quoteId);
    
    if (postIndex !== -1) {
      myPosts[postIndex].isThoughtsExpanded = !myPosts[postIndex].isThoughtsExpanded;
      this.setData({ myPosts: [...myPosts] });
    }
  },

  /**
   * 关于我们
   */
  goAbout() {
    wx.navigateTo({
      url: '/pages/about/index'
    });
  },

  /**
   * 分享个人主页
   */
  shareProfile() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },

  /**
   * 退出登录
   */
  logout() {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除本地数据
          wx.removeStorageSync('userInfo');
          wx.removeStorageSync('access_token');
          wx.removeStorageSync('userId');
          wx.removeStorageSync('openid');
          
          // 清除欢迎卡片显示记录
          wx.removeStorageSync('lastWelcomeTime');
          wx.removeStorageSync('lastWelcomeUserId');
          
          // 重置全局数据
          app.globalData.userInfo = null;
          app.globalData.userProfile = null;
          app.globalData.userId = null;
          app.globalData.openid = null;
          
          // 跳转到登录页
          wx.reLaunch({
            url: '/pages/login/login'
          });
        }
      }
    });
  }
});
